package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.utils.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:uid:";

    public void addItemToCart(Cart cart) {
        // 0.获取用户id
        String key = KEY_PREFIX + UserHolder.getUser().getId();

        // 1.获取redis的hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 2.判断是否存在
        String skuId = cart.getSkuId().toString();
        Boolean exists = hashOps.hasKey(skuId);
        if (BooleanUtils.isTrue(exists)) {
            // 3.如果存在，取出已经存在的
            String json = hashOps.get(skuId);
            Integer num = cart.getNum();
            cart = JsonUtils.toBean(json, Cart.class);
            // 4.修改数量
            cart.setNum(num + cart.getNum());
        }
        // 5.如果不存在，直接新增
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 0.获取用户id
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 1.获取redis的hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 2.查询用户的购物车的列表
        List<String> values = hashOps.values();
        if(CollectionUtils.isEmpty(values)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 3.转换数据
        return values.stream()
                .map(json -> JsonUtils.toBean(json, Cart.class))
                .collect(Collectors.toList());
    }
}
